#include "lexer.h"

Token* Lexer::scan() {
       // eat whitespace
       for (;;is.get()) {
            if (is.peek() == ' ' || is.peek() == '\t') continue;
            else if (is.peek() == '\n') return new Token(TS_EOF);
            else if (!is.good()) return new Token(TS_EOF);
            else break;
        }    
        switch (is.peek()) {
            case '+': is.get(); return new Token(TS_ADD);
            case '-': is.get(); return new Token(TS_SUB);
            case '*': is.get(); return new Token(TS_MUL);
            case '/': is.get(); return new Token(TS_DIV);
            case '(': is.get(); return new Token(TS_LPAR);
            case ')': is.get(); return new Token(TS_RPAR);
        }
        if (isdigit(is.peek())) {
            int v = 0;
            do {
                v = 10*v + is.peek()-0x30;
                is.get();
            } while (isdigit(is.peek()));
            if (is.peek() != '.') return new Num(v);
            double x = v; double d = 10;
            for (;;) {
                is.get();
                if (!isdigit(is.peek())) break;
                x = x + (is.peek()-0x30) / d; d = d *10;
            }        
            return new Real(x);
        }
    }

